package com.freeman.cement.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.freeman.cement.entity.hikvision.EventElement;
import com.freeman.cement.service.EventAnalysisService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

//使用那种解析就在这个实现类上加注解
@Service
public class EventAnalysisServiceImplV2 implements EventAnalysisService {

    private static final Logger logger = LoggerFactory.getLogger(EventAnalysisServiceImplV2.class);

    private String getJsonValue(String text, String key) {
        String value = "";
        if (StringUtils.contains(text, key)) {
            int start = text.indexOf("imageUrl") + 11;
            String remain = text.substring(0, start);
            value = remain.substring(0, remain.indexOf('\"'));


        }
        return value;
    }

    private String getValue(JSONObject jsonObject, String key) {
        return jsonObject.containsKey(key) ? jsonObject.getString(key) : "";
    }

    @Override
    public List<EventElement> analysisEvent(String params) {
        /**
         * 报文解析是要解析出
         * 1、eventId 事件Id
         * 2、eventType 事件类型
         * 3、happenTime 发生事件
         * 4、cameraIndexCode 摄像头编号
         * 5、imageUrl 图片地址
         *
         * 下面解析方法要求:
         * 1、events必须为Events[]数组
         */
        List<EventElement> list = new ArrayList<>();
        if (StringUtils.contains(params, "events")) {
            try {
                JSONObject jparams = JSONObject.parseObject(params);
                //Events[]是数组
                JSONArray events = jparams.getJSONArray("events");
                if (events != null && events.size() > 0) {
                    list = new ArrayList<>();
                    for (int i = 0; i < events.size(); i++) {
                        //判断是否为联动事件
                        String srcType = getValue(events.getJSONObject(i), "srcType");
                        //java中用equals方法比较的是字符串的内容是否相同
                        if (srcType.equals("eventRule")) {
                            JSONArray eventDetails = events.getJSONObject(i).getJSONArray("eventDetails");
                            for (int j = 0; j < eventDetails.size(); j++) {
                                String eventId = getValue(eventDetails.getJSONObject(j), "eventOriginalId");
                                if (!list.stream().anyMatch(s -> s.getEventId().equals(eventId))) {
                                    EventElement element = new EventElement();
                                    //基本报警信息
                                    element.setEventId(eventId);
                                    element.setEventType(getValue(eventDetails.getJSONObject(j), "eventType"));
                                    element.setSrcIndex(getValue(eventDetails.getJSONObject(j), "srcIndex"));
                                    element.setSrcName(getValue(eventDetails.getJSONObject(j), "srcName"));
                                    element.setSrcType(getValue(eventDetails.getJSONObject(j), "srcType"));
                                    element.setRegionIndexCode(getValue(eventDetails.getJSONObject(j), "regionIndexCode"));
                                    element.setRegionName(getValue(eventDetails.getJSONObject(j), "regionName"));
                                    //解析联动事件中可能有的报警图片
                                    JSONObject data = eventDetails.getJSONObject(j).getJSONObject("data");
                                    if (data != null) {
                                        JSONObject aiopData = data.getJSONObject("AIOPResultData");
                                        if (aiopData != null) {
                                            String imageUrl = aiopData.getString("imageUrl");
                                            element.setImageUrl(imageUrl);
                                        }
                                    }

                                    // 处理联动事件中的 overheadInfo
                                    try {
                                        JSONArray linkageResult = events.getJSONObject(i).getJSONArray("linkageResult");
                                        if (linkageResult != null && linkageResult.size() > 0) {
                                            JSONObject linkageObj = linkageResult.getJSONObject(0);
                                            if (linkageObj.containsKey("content")) {
                                                JSONArray content = linkageObj.getJSONArray("content");
                                                if (content != null && content.size() > 0) {
                                                    JSONObject contentObj = content.getJSONObject(0);
                                                    if (contentObj.containsKey("overheadInfo")) {
                                                        JSONArray overheadInfoArray = contentObj.getJSONArray("overheadInfo");
                                                        if (overheadInfoArray != null && overheadInfoArray.size() > 0) {
                                                            String overheadInfoStr = overheadInfoArray.toJSONString();
                                                            if (StringUtils.isNotBlank(overheadInfoStr)) {
                                                                logger.info("解析到联动事件的 overheadInfo: {}", overheadInfoStr);
                                                                element.setOverheadInfo(overheadInfoStr);
                                                                logger.info("成功设置联动事件的 overheadInfo");
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    } catch (Exception e) {
                                        logger.error("解析联动事件的 overheadInfo 时发生错误: {}", e.getMessage(), e);
                                    }

                                    list.add(element);
                                }
                            }

                            for (EventElement s : list) {
                                s.setHappenTime(getValue(events.getJSONObject(i), "happenTime"));
                            }
                        }
                        //原始事件
                        else {
                            String eventId = getValue(events.getJSONObject(i), "eventId");
                            if (!list.stream().anyMatch(s -> s.getEventId().equals(eventId))) {
                                EventElement element = new EventElement();
                                element.setEventId(eventId);
                                element.setEventType(getValue(events.getJSONObject(i), "eventType"));
                                element.setSrcIndex(getValue(events.getJSONObject(i), "srcIndex"));
                                element.setSrcName(getValue(events.getJSONObject(i), "srcName"));
                                element.setSrcType(getValue(events.getJSONObject(i), "srcType"));
                                element.setRegionIndexCode(getValue(events.getJSONObject(i), "regionIndexCode"));
                                element.setRegionName(getValue(events.getJSONObject(i), "regionName"));
                                element.setHappenTime(getValue(events.getJSONObject(i), "happenTime"));
                                
                                // 从data.AIOPResultData.imageUrl中获取图片URL
                                JSONObject data = events.getJSONObject(i).getJSONObject("data");
                                if (data != null) {
                                    JSONObject aiopData = data.getJSONObject("AIOPResultData");
                                    if (aiopData != null) {
                                        String imageUrl = aiopData.getString("imageUrl");
                                        element.setImageUrl(imageUrl);
                                    }
                                }

                                // 处理原始事件中的 overheadInfo
                                try {
                                    Object overheadInfoObj = events.getJSONObject(i).get("overheadInfo");
                                    String overheadInfoStr = null;
                                    if (overheadInfoObj instanceof JSONArray) {
                                        // 如果是数组，保存整个数组
                                        JSONArray overheadInfoArray = (JSONArray) overheadInfoObj;
                                        if (overheadInfoArray != null && overheadInfoArray.size() > 0) {
                                            overheadInfoStr = overheadInfoArray.toJSONString();
                                        }
                                    } else if (overheadInfoObj instanceof String) {
                                        // 如果是字符串，尝试解析为 JSON 对象或数组
                                        try {
                                            Object jsonObj = JSONObject.parse((String) overheadInfoObj);
                                            overheadInfoStr = jsonObj.toString();
                                        } catch (Exception e) {
                                            // 如果解析失败，直接使用字符串
                                            overheadInfoStr = (String) overheadInfoObj;
                                        }
                                    } else if (overheadInfoObj instanceof JSONObject) {
                                        // 如果是 JSON 对象，转换为字符串
                                        overheadInfoStr = ((JSONObject) overheadInfoObj).toJSONString();
                                    }

                                    if (StringUtils.isNotBlank(overheadInfoStr)) {
                                        logger.info("解析到原始事件的 overheadInfo: {}", overheadInfoStr);
                                        element.setOverheadInfo(overheadInfoStr);
                                        logger.info("成功设置原始事件的 overheadInfo");
                                    } else {
                                        logger.warn("原始事件中未找到 overheadInfo 或为空");
                                    }
                                } catch (Exception e) {
                                    logger.error("解析原始事件的 overheadInfo 时发生错误: {}", e.getMessage(), e);
                                }

                                list.add(element);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                System.out.println("报文解析出错: \n");
                e.printStackTrace();
                list = null;
            }
        }
        return list;
    }


    @Override
    public List<EventElement> analysisEventTest(String params) {
        /**
         * 报文解析是要解析出
         * 1、eventId 事件Id
         * 2、eventType 事件类型
         * 3、happenTime 发生事件
         * 4、cameraIndexCode 摄像头编号
         * 5、imageUrl 图片地址
         *
         * 下面解析方法要求:
         * 1、events必须为Events[]数组
         */
        List<EventElement> list = new ArrayList<>();
        try {
            if (StringUtils.isBlank(params)) {
                logger.warn("传入的 params 为空");
                return list;
            }

            logger.info("开始解析 params: {}", params);
            JSONObject jparams = JSONObject.parseObject(params);
            if (jparams == null) {
                logger.warn("解析 params 为 JSONObject 失败");
                return list;
            }

            // 获取 params 对象
            JSONObject paramsObj = jparams.getJSONObject("params");
            if (paramsObj == null) {
                logger.warn("params 中不包含 params 对象");
                return list;
            }

            if (!paramsObj.containsKey("events")) {
                logger.warn("params 中不包含 events 字段");
                return list;
            }

            JSONArray events = paramsObj.getJSONArray("events");
            if (events == null || events.isEmpty()) {
                logger.warn("events 数组为空");
                return list;
            }

            for (int i = 0; i < events.size(); i++) {
                //判断是否为联动事件
                String srcType = getValue(events.getJSONObject(i), "srcType");
                //java中用equals方法比较的是字符串的内容是否相同
                if (srcType.equals("eventRule")) {
                    JSONArray eventDetails = events.getJSONObject(i).getJSONArray("eventDetails");
                    for (int j = 0; j < eventDetails.size(); j++) {
                        String eventId = getValue(eventDetails.getJSONObject(j), "eventOriginalId");
                        if (!list.stream().anyMatch(s -> s.getEventId().equals(eventId))) {
                            EventElement element = new EventElement();
                            //基本报警信息
                            element.setEventId(eventId);
                            element.setEventType(getValue(eventDetails.getJSONObject(j), "eventType"));
                            element.setSrcIndex(getValue(eventDetails.getJSONObject(j), "srcIndex"));
                            element.setSrcName(getValue(eventDetails.getJSONObject(j), "srcName"));
                            element.setSrcType(getValue(eventDetails.getJSONObject(j), "srcType"));
                            element.setRegionIndexCode(getValue(eventDetails.getJSONObject(j), "regionIndexCode"));
                            element.setRegionName(getValue(eventDetails.getJSONObject(j), "regionName"));
                            //解析联动事件中可能有的报警图片
                            JSONObject data = eventDetails.getJSONObject(j).getJSONObject("data");
                            if (data != null) {
                                JSONObject aiopData = data.getJSONObject("AIOPResultData");
                                if (aiopData != null) {
                                    String imageUrl = aiopData.getString("imageUrl");
                                    element.setImageUrl(imageUrl);
                                }
                            }

                            // 处理联动事件中的 overheadInfo
                            try {
                                JSONArray linkageResult = events.getJSONObject(i).getJSONArray("linkageResult");
                                if (linkageResult != null && linkageResult.size() > 0) {
                                    JSONObject linkageObj = linkageResult.getJSONObject(0);
                                    if (linkageObj.containsKey("content")) {
                                        JSONArray content = linkageObj.getJSONArray("content");
                                        if (content != null && content.size() > 0) {
                                            JSONObject contentObj = content.getJSONObject(0);
                                            if (contentObj.containsKey("overheadInfo")) {
                                                JSONArray overheadInfoArray = contentObj.getJSONArray("overheadInfo");
                                                if (overheadInfoArray != null && overheadInfoArray.size() > 0) {
                                                    String overheadInfoStr = overheadInfoArray.toJSONString();
                                                    if (StringUtils.isNotBlank(overheadInfoStr)) {
                                                        logger.info("解析到联动事件的 overheadInfo: {}", overheadInfoStr);
                                                        element.setOverheadInfo(overheadInfoStr);
                                                        logger.info("成功设置联动事件的 overheadInfo");
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                logger.error("解析联动事件的 overheadInfo 时发生错误: {}", e.getMessage(), e);
                            }

                            list.add(element);
                        }
                    }

                    for (EventElement s : list) {
                        s.setHappenTime(getValue(events.getJSONObject(i), "happenTime"));
                    }
                }
                //原始事件
                else {
                    String eventId = getValue(events.getJSONObject(i), "eventId");
                    if (!list.stream().anyMatch(s -> s.getEventId().equals(eventId))) {
                        EventElement element = new EventElement();
                        element.setEventId(eventId);
                        element.setEventType(getValue(events.getJSONObject(i), "eventType"));
                        element.setSrcIndex(getValue(events.getJSONObject(i), "srcIndex"));
                        element.setSrcName(getValue(events.getJSONObject(i), "srcName"));
                        element.setSrcType(getValue(events.getJSONObject(i), "srcType"));
                        element.setRegionIndexCode(getValue(events.getJSONObject(i), "regionIndexCode"));
                        element.setRegionName(getValue(events.getJSONObject(i), "regionName"));
                        element.setHappenTime(getValue(events.getJSONObject(i), "happenTime"));
                        
                        // 从data.AIOPResultData.imageUrl中获取图片URL
                        JSONObject data = events.getJSONObject(i).getJSONObject("data");
                        if (data != null) {
                            JSONObject aiopData = data.getJSONObject("AIOPResultData");
                            if (aiopData != null) {
                                String imageUrl = aiopData.getString("imageUrl");
                                element.setImageUrl(imageUrl);
                            }
                        }

                        // 处理原始事件中的 overheadInfo
                        try {
                            Object overheadInfoObj = events.getJSONObject(i).get("overheadInfo");
                            String overheadInfoStr = null;
                            if (overheadInfoObj instanceof JSONArray) {
                                // 如果是数组，保存整个数组
                                JSONArray overheadInfoArray = (JSONArray) overheadInfoObj;
                                if (overheadInfoArray != null && overheadInfoArray.size() > 0) {
                                    overheadInfoStr = overheadInfoArray.toJSONString();
                                }
                            } else if (overheadInfoObj instanceof String) {
                                // 如果是字符串，尝试解析为 JSON 对象或数组
                                try {
                                    Object jsonObj = JSONObject.parse((String) overheadInfoObj);
                                    overheadInfoStr = jsonObj.toString();
                                } catch (Exception e) {
                                    // 如果解析失败，直接使用字符串
                                    overheadInfoStr = (String) overheadInfoObj;
                                }
                            } else if (overheadInfoObj instanceof JSONObject) {
                                // 如果是 JSON 对象，转换为字符串
                                overheadInfoStr = ((JSONObject) overheadInfoObj).toJSONString();
                            }

                            if (StringUtils.isNotBlank(overheadInfoStr)) {
                                logger.info("解析到原始事件的 overheadInfo: {}", overheadInfoStr);
                                element.setOverheadInfo(overheadInfoStr);
                                logger.info("成功设置原始事件的 overheadInfo");
                            } else {
                                logger.warn("原始事件中未找到 overheadInfo 或为空");
                            }
                        } catch (Exception e) {
                            logger.error("解析原始事件的 overheadInfo 时发生错误: {}", e.getMessage(), e);
                        }

                        list.add(element);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("报文解析出错: {}", e.getMessage(), e);
            list = null;
        }
        return list;
    }

}